<template>
  <view class="container" v-if="userId">
    <scroll-view scroll-y="true" class="chat-list">
      <u-swipe-action v-if="chatLists && chatLists.length">
        <u-swipe-action-item
          :options="swipeProps"
          @click="handleChatItem(item)"
          v-for="item in chatLists"
          :key="item.groupId"
          :index="item.groupId"
        >
          <view class="chat-item" @tap="onChat(item)">
            <img :src="item.avatarUrl" alt="" class="user_img" />
            <view class="info">
              <view class="name">{{ item.nickname }}</view>
              <view class="msg">
                <u-text
                  class="text"
                  :lines="1"
                  :text="item.content || '暂无消息'"
                ></u-text>
              </view>
            </view>
          </view>
        </u-swipe-action-item>
      </u-swipe-action>
      <view v-else class="empty-box">
        <u-empty mode="message" icon="/static/icon/empty.jpeg"> </u-empty>
      </view>
    </scroll-view>

    <Tabbar
      :fixed="false"
      ref="tabber"
      :current="0"
      :tab-bar-list="tabBerLists"
    />
  </view>
</template>

<script setup>
import arr from "@/utils/tabbar";
import { chatList, setRedis, clearChatHistory } from "@/global/chatApi";
import { ref } from "vue";
import useChat from "@/store/useChat.js";
import useLogin from "@/store/useLogin.js";
import useAgent from "@/store/useAgent.js";
import useWs from "@/store/useWs.js";
const useWsStore = useWs();
const useChatStore = useChat();
const useAgentStore = useAgent();
const useLoginStore = useLogin();
const tabBerLists = ref(arr);
const chatLists = ref([]);
const userId = ref("");
const swipeProps = ref([
  {
    text: "删除",
    style: {
      backgroundColor: "red",
    },
  },
]);
const onChat = (item) => {
  //更新store的会话id
  useChatStore.selectSession(item.groupId);
  //初始化本次选择的对话对象本地存储
  useChatStore.checkNewUserChat(item);
  //更新当前智能体ID
  useAgentStore.agentId = item.agentId;
  //缓存智能体信息
  setRedis({
    userId: uni.getStorageSync("currentUserId"),
    agentId: item.agentId,
  }).then((res) => {});
  nextTick(() => {
    let query = `agentId=${item.agentId}&groupId=${item.groupId}&nickname=${item.nickname}`;
    uni.navigateTo({
      url: "/pages/index/chat?" + query,
    });
  });
};

const getChatList = () => {
  userId.value = uni.getStorageSync("currentUserId");

  chatList({
    userId: userId.value,
  })
    .then((res) => {
      chatLists.value = res.data;
      useChatStore.initChatData(res.data);
    })
    .catch((err) => {
      useChatStore.initChatData([]);
      chatLists.value = useChatStore.sessions;
    });
};

//删除聊天记录
const handleChatItem = (data) => {
  uni.showModal({
    title: "温馨提示",
    content: "删除后不可恢复，确定要删除吗",
    success: function (res) {
      if (res.confirm) {
        clearChatHistory({ groupId: data.groupId }).then((res) => {
          if (res && res.code == 200) {
            uni.showToast({
              icon: "none",
              title: "已删除",
            });
            getChatList();
          }
        });

        //todo 调api
      } else if (res.cancel) {
        console.log("用户点击取消");
      }
    },
  });
};

onLoad(() => {
  uni.hideTabBar();
});

onShow(() => {
  useWsStore._ws.close && useWsStore._ws.close();
  if (!userId.value) {
    useLoginStore.userLogin(getChatList);
  } else {
    getChatList();
  }
});
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .empty-box {
    margin-top: 100rpx;
  }
  .chat-list {
    flex: 1;
    min-height: 0;
  }

  .chat-item {
    width: 100%;
    height: 180rpx;
    padding: 10rpx 20px;
    display: flex;
    align-items: center;
    box-sizing: border-box;

    .user_img {
      width: 120rpx;
      height: 120rpx;
      border-radius: 50%;
      margin-right: 25rpx;
    }

    .info {
      flex: 1;
      .name {
        font-size: 30rpx;
        font-weight: bold;
      }
      .msg {
        display: flex;
        justify-content: space-between;
        font-size: 20rpx;
        align-items: flex-end;
        font-weight: 400;
        margin-top: 10rpx;
        .text {
          flex: 1;
        }
        .time {
          width: 150rpx;
          text-align: right;
        }
      }
    }
    &:active {
      background-color: #f0f0f0;
    }
  }
}
</style>
